import { SetupContext, defineComponent, ref, watch } from 'vue';
import { dynamicViewProps, DynamicViewProps } from './dynamic-view.props';
import { componentMap, componentPropsConverter } from './component-maps';

const FDynamicView = defineComponent({
    name: 'FDynamicView',
    props: dynamicViewProps,
    emits: ['update:modelValue'],
    setup(props: DynamicViewProps, context: SetupContext) {
        const modelValue = ref(props.modelValue);

        function renderContent(content: any[]) {
            return content.map((contentSchema: any) => {
                return <FDynamicView v-model={contentSchema}></FDynamicView>;
            });
        }

        function render(viewSchem: any) {
            const componentKey = viewSchem.type;
            const Component = componentMap[componentKey];

            const propsConverter = componentPropsConverter[componentKey];
            const viewProps = propsConverter ? propsConverter(viewSchem) : {};

            const hasContent = viewSchem.content && !!viewSchem.content.length;
            return hasContent ? (
                <Component {...viewProps}>{renderContent(modelValue.value.content)}</Component>
            ) : Component ? (
                <Component {...viewProps}></Component>
            ) : (
                <div></div>
            );
        }

        watch(
            () => props.modelValue,
            (value: any) => {
                modelValue.value = value;
                return render(modelValue.value);
            }
        );

        return () => {
            return render(modelValue.value);
        };
    }
});
export default FDynamicView;
